package com.ruoyi.common.wx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.wx.domain.WxUserToken;
import com.ruoyi.common.wx.mapper.WxUserTokenMapper;
import com.ruoyi.common.wx.service.IWxUserTokenService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;

@Service
public class WxUserTokenServiceImpl extends ServiceImpl<WxUserTokenMapper, WxUserToken> implements IWxUserTokenService {

    @Override
    public String createToken(Long userId) {
        String token = IdUtils.fastUUID();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        remove(queryWrapper);
        WxUserToken userToken = new WxUserToken().setUserId(userId).setToken(token).setExpireTime(DateUtils.addMonths(new Date(), 7));
        if (save(userToken)) {
            return token;
        }
        throw new RuntimeException("生成token失败！");
    }

    @Override
    public Boolean refreshToken(WxUserToken token) {
        Assert.notNull(token, "无效的token!");

        token.setExpireTime(DateUtils.addDays(new Date(), 7));
        return updateById(token);
    }
}
